package com.cys.markdown.doc.admin.common.resolver;

import com.cys.markdown.doc.admin.common.annotation.CurrentUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * CurrentUser注解的参数自动设值【简化获取当前登录人信息的方法】
 * @author : caiyushen
 * @createDate 2019-01-01
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    public CurrentUserMethodArgumentResolver() {
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Object result = null;

        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();

        if (currentUser != null && parameter.hasParameterAnnotation(CurrentUser.class)
                && !parameter.getParameterType().isAssignableFrom(Subject.class)) {

            CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class);

            String annVal = currentUserAnnotation.value();
            switch (annVal) {
                case "sysUserId":
                    result = session.getAttribute("sysUserId");
                    break;
                default:
                    break;
            }
        }

        return result;
    }
}
